<template>
  <SEO
    :title="seoTitle"
    :description="seoDescription"
    :keywords="seoKeywords"
    :image="seoImage"
    :canonical="seoCanonical"
    og-type="product"
    :price="product.price"
    :availability="seoAvailability"
    :json-ld="productSchema"
  />
  <ShopLayout>
    <!-- Product Hero Section - 移动端优化 -->
    <div class="bg-gray-100 min-h-screen">
      <div class="max-w-7xl mx-auto px-4 sm:px-8 lg:px-24">
        <!-- Product Overview -->
        <div class="py-8 sm:py-12 lg:py-24">
          <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 lg:gap-20 items-start">
            <!-- Product Images -->
            <div class="order-2 lg:order-1">
              <!-- Main Product Image -->
              <div class="relative">
                <div class="aspect-square bg-white rounded-2xl sm:rounded-3xl p-4 sm:p-6 lg:p-8 shadow-sm overflow-hidden">
                  <img 
                    :src="selectedImage || (product.images && product.images[0]?.image_path) || product.image || '/images/product-placeholder.svg'" 
                    :alt="product.name" 
                    class="w-full h-full object-contain transition-all duration-300"
                    loading="lazy"
                  />
                </div>
                
                <!-- Product Badge -->
                <div v-if="product.is_featured" class="absolute top-3 left-3 sm:top-4 sm:left-4 bg-gray-900 text-white px-2 py-1 sm:px-3 sm:py-1 rounded-full text-xs sm:text-sm font-medium">
                  推荐
                </div>
                <div v-if="product.discount_percentage" class="absolute top-3 right-3 sm:top-4 sm:right-4 bg-red-500 text-white px-2 py-1 sm:px-3 sm:py-1 rounded-full text-xs sm:text-sm font-medium">
                  -{{ product.discount_percentage }}%
                </div>
              </div>
              
              <!-- Image Indicators -->
                <div class="flex gap-2 mt-4 sm:mt-6 justify-center">
                  <button
                    v-for="(image, index) in (product.images || [{image_path: '/images/product-placeholder.svg'}])"
                    :key="index"
                    @click="selectedImage = image.image_path"
                    :class="[
                      'w-2 h-2 rounded-full transition-all duration-200 active:scale-110',
                      selectedImage === image.image_path 
                        ? 'bg-gray-900' 
                        : 'bg-gray-300 active:bg-gray-400'
                    ]"
                  >
                  </button>
                </div>
            </div>

            <!-- Product Info -->
            <div class="order-1 lg:order-2">
              <div class="max-w-lg">
                <!-- Product Title -->
                <h1 class="text-2xl sm:text-3xl lg:text-4xl font-light text-gray-900 mb-3 sm:mb-4 leading-tight">{{ product.name }}</h1>
                
                <!-- Product Subtitle -->
                <p v-if="product.subtitle" class="text-base sm:text-lg text-gray-500 mb-3 sm:mb-4">{{ product.subtitle }}</p>
                
                <!-- Product Description -->
                <p class="text-base sm:text-lg text-gray-600 mb-4 sm:mb-6 leading-relaxed">{{ product.description }}</p>
                
                <!-- Price Section -->
                <div class="mb-6 sm:mb-8">
                  <div class="flex items-baseline gap-2 sm:gap-3 mb-2">
                    <span v-if="product.product_type === 'single'" class="text-2xl sm:text-3xl font-medium text-gray-900">¥{{ currentPrice.toLocaleString() }}</span>
                    <span v-else-if="selectedVariant" class="text-2xl sm:text-3xl font-medium text-gray-900">¥{{ currentPrice.toLocaleString() }}</span>
                    <span v-else class="text-2xl sm:text-3xl font-medium text-gray-500">请选择规格</span>
                    
                    <span v-if="selectedVariant && selectedVariant.compare_price" class="text-base sm:text-lg text-gray-500 line-through">¥{{ selectedVariant.compare_price.toLocaleString() }}</span>
                    <span v-else-if="product.product_type === 'single' && product.compare_price" class="text-base sm:text-lg text-gray-500 line-through">¥{{ product.compare_price.toLocaleString() }}</span>
                  </div>
                  <div class="flex items-center gap-3 sm:gap-4 text-xs sm:text-sm">
                    <span v-if="selectedVariant && selectedVariant.discount_percentage" class="text-red-600 font-medium">节省 ¥{{ (selectedVariant.compare_price - selectedVariant.price).toLocaleString() }}</span>
                    <span v-else-if="product.product_type === 'single' && product.discount_percentage" class="text-red-600 font-medium">节省 ¥{{ (product.compare_price - product.price).toLocaleString() }}</span>
                    <span v-else-if="product.product_type === 'multi_variant' && !selectedVariant" class="text-gray-500">选择规格后显示价格</span>
                    <span v-else class="text-gray-500">含增值税</span>
                  </div>
                </div>

                <!-- Specifications（仅多规格商品显示） -->
                <div v-if="product.product_type === 'multi_variant' && specifications.length > 0" class="space-y-6 mb-8">
                  <div v-for="spec in specifications" :key="spec.key" class="space-y-4">
                    <div class="flex items-center justify-between">
                      <h3 class="text-lg font-medium text-gray-900">{{ spec.name }}</h3>
                      <span v-if="selectedSpecs[spec.key]" class="text-sm text-gray-500">{{ selectedSpecs[spec.key] }}</span>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                      <button
                        v-for="option in spec.options"
                        :key="option.value"
                        @click="selectSpec(spec.key, option.value)"
                        :disabled="getSpecOptionStockStatus(spec.key, option.value) === 'unavailable' || getSpecOptionStockStatus(spec.key, option.value) === 'out_of_stock'"
                        :class="[
                          'relative px-4 py-3 rounded-xl text-sm font-medium transition-all duration-200 border-2 z-10',
                          selectedSpecs[spec.key] === option.value
                            ? 'bg-gray-900 text-white border-gray-900'
                            : getSpecOptionStockStatus(spec.key, option.value) === 'unavailable' || getSpecOptionStockStatus(spec.key, option.value) === 'out_of_stock'
                            ? 'bg-gray-50 text-gray-400 border-gray-200 cursor-not-allowed line-through'
                            : getSpecOptionStockStatus(spec.key, option.value) === 'low_stock'
                            ? 'bg-white text-gray-700 border-amber-400 hover:border-amber-500 hover:bg-amber-50 cursor-pointer'
                            : 'bg-white text-gray-700 border-gray-200 hover:border-gray-400 hover:bg-gray-50 cursor-pointer'
                        ]"
                      >
                        {{ option.name }}
                        <!-- 低库存标签 -->
                        <span 
                          v-if="getSpecOptionStockStatus(spec.key, option.value) === 'low_stock' && selectedSpecs[spec.key] !== option.value"
                          class="absolute -top-1 -right-1 inline-flex items-center justify-center w-5 h-5 text-xs font-semibold text-white bg-amber-500 rounded-full"
                        >
                          !
                        </span>
                        <!-- 缺货标签 -->
                        <span 
                          v-if="getSpecOptionStockStatus(spec.key, option.value) === 'out_of_stock'"
                          class="absolute -top-1 -right-1 inline-flex items-center justify-center px-1.5 py-0.5 text-xs font-semibold text-white bg-gray-400 rounded-full"
                        >
                          售罄
                        </span>
                      </button>
                    </div>
                  </div>
                  
                  <!-- 错误提示 -->
                  <div v-if="variantError" class="bg-red-50 border border-red-200 rounded-lg p-4">
                    <div class="flex items-center">
                      <svg class="w-5 h-5 text-red-400 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                      <span class="text-red-700 text-sm">{{ variantError }}</span>
                    </div>
                  </div>
                </div>

                <!-- Quantity & Stock -->
                <div class="mb-8">
                  <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-medium text-gray-900">数量</h3>
                    <div class="flex items-center gap-2">
                      <!-- 库存警告 -->
                      <span 
                        v-if="selectedVariant && selectedVariant.stock_quantity <= 5 && selectedVariant.stock_quantity > 0" 
                        class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-amber-100 text-amber-800"
                      >
                        <svg class="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                          <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
                        </svg>
                        仅剩 {{ currentStock }} 件
                      </span>
                      <!-- 正常库存 -->
                      <span v-else class="text-sm text-gray-500">库存: {{ currentStock }} 件</span>
                    </div>
                  </div>
                  <div class="flex items-center gap-4">
                    <button
                      @click="quantity > 1 ? quantity-- : null"
                      :disabled="quantity <= 1"
                      class="w-12 h-12 rounded-xl border-2 border-gray-200 flex items-center justify-center hover:bg-gray-50 hover:border-gray-300 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
                    >
                      <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 12H4" />
                      </svg>
                    </button>
                    <div class="w-16 h-12 bg-gray-50 rounded-xl flex items-center justify-center">
                      <span class="text-lg font-medium text-gray-900">{{ quantity }}</span>
                    </div>
                    <button
                      @click="quantity < currentStock ? quantity++ : null"
                      :disabled="quantity >= currentStock"
                      class="w-12 h-12 rounded-xl border-2 border-gray-200 flex items-center justify-center hover:bg-gray-50 hover:border-gray-300 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
                    >
                      <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                      </svg>
                    </button>
                  </div>
                </div>

                <!-- Action Buttons -->
                <div class="space-y-3">
                  <!-- 对比按钮 (暂时注释) -->
                  <!-- <CompareButton :product-id="product.id" class="w-full" /> -->
                  
                  <button
                    @click="addToCart"
                    :disabled="!canAddToCart"
                    :class="[
                      'w-full py-4 px-8 rounded-2xl text-lg font-medium transition-all duration-200 flex items-center justify-center gap-2',
                      canAddToCart 
                        ? 'bg-gray-900 text-white hover:bg-gray-800' 
                        : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                    ]"
                  >
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4m0 0L7 13m0 0l-2.5 5M7 13l2.5 5m6-5v6a2 2 0 01-2 2H9a2 2 0 01-2-2v-6m8 0V9a2 2 0 00-2-2H9a2 2 0 00-2 2v4.01" />
                    </svg>
                    {{ addToCartButtonText }}
                  </button>
                  <button
                    @click="buyNow"
                    :disabled="!canAddToCart"
                    :class="[
                      'w-full py-4 px-8 rounded-2xl text-lg font-medium transition-all duration-200 flex items-center justify-center gap-2',
                      canAddToCart 
                        ? 'border-2 border-gray-900 text-gray-900 hover:bg-gray-900 hover:text-white' 
                        : 'border-2 border-gray-300 text-gray-500 cursor-not-allowed'
                    ]"
                  >
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                    </svg>
                    {{ buyNowButtonText }}
                  </button>
                </div>

                <!-- Features -->
                <div class="mt-12">
                  <h3 class="text-lg font-medium text-gray-900 mb-6">产品特性</h3>
                  <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div v-for="feature in features" :key="feature" class="flex items-start gap-3 p-4 bg-gray-50 rounded-xl">
                      <div class="w-6 h-6 bg-green-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
                        <svg class="w-4 h-4 text-green-600" fill="currentColor" viewBox="0 0 20 20">
                          <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                        </svg>
                      </div>
                      <span class="text-gray-700 text-sm leading-relaxed">{{ feature }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Product Details Section -->
    <div class="bg-white">
      <div class="max-w-7xl mx-auto px-8 sm:px-16 lg:px-24 py-20">
        <!-- Technical Specifications -->
        <div v-if="technicalSpecs && technicalSpecs.length > 0" class="mb-20">
          <div class="text-center mb-12">
            <h2 class="text-3xl font-light text-gray-900 mb-4">技术规格</h2>
            <p class="text-gray-600">了解产品的详细技术参数</p>
          </div>
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
            <div v-for="spec in technicalSpecs" :key="spec.category" class="bg-gray-50 rounded-2xl p-4 sm:p-6 hover:shadow-md transition-shadow duration-200">
              <div class="flex items-center gap-2 sm:gap-3 mb-3 sm:mb-4">
                <div class="w-7 h-7 sm:w-8 sm:h-8 bg-gray-900 rounded-lg flex items-center justify-center flex-shrink-0">
                  <svg class="w-3.5 h-3.5 sm:w-4 sm:h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                </div>
                <h3 class="text-base sm:text-lg font-medium text-gray-900">{{ spec.category }}</h3>
              </div>
              <ul class="space-y-2 sm:space-y-3">
                <li v-for="item in spec.items" :key="item.name" class="flex flex-col sm:flex-row sm:justify-between sm:items-center py-2 border-b border-gray-200 last:border-b-0 gap-1">
                  <span class="text-gray-600 text-xs sm:text-sm">{{ item.name }}</span>
                  <span class="text-gray-900 font-medium text-sm sm:text-sm text-right">{{ item.value }}</span>
                </li>
              </ul>
            </div>
          </div>
        </div>
        
        <!-- Long Description -->
        <div v-if="product.long_description" class="mb-20">
          <div class="text-center mb-12">
            <h2 class="text-3xl font-light text-gray-900 mb-4">产品详情</h2>
            <p class="text-gray-600">了解更多关于此产品的信息</p>
          </div>
          <div class="prose prose-lg max-w-4xl mx-auto">
            <div class="text-gray-700 leading-relaxed whitespace-pre-line" v-html="product.long_description"></div>
          </div>
        </div>

        <!-- Customer Reviews -->
        <div v-if="reviews && reviews.length > 0" class="mb-20">
          <div class="text-center mb-12">
            <h2 class="text-3xl font-light text-gray-900 mb-4">用户评价</h2>
            <p class="text-gray-600">看看其他用户的使用体验</p>
            
            <!-- 评价统计 -->
            <div class="mt-8 flex items-center justify-center gap-8">
              <div class="text-center">
                <div class="text-3xl font-light text-gray-900 mb-1">{{ averageRating }}</div>
                <div class="flex items-center justify-center gap-1 mb-2">
                  <svg v-for="i in 5" :key="i" class="w-5 h-5" :class="i <= averageRating ? 'text-yellow-400' : 'text-gray-300'" fill="currentColor" viewBox="0 0 20 20">
                    <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                  </svg>
                </div>
                <p class="text-sm text-gray-500">基于 {{ reviews.length }} 条评价</p>
              </div>
              
              <div class="h-12 w-px bg-gray-300"></div>
              
              <div class="text-center">
                <div class="text-2xl font-medium text-gray-900 mb-1">{{ reviews.length }}</div>
                <p class="text-sm text-gray-500">用户评价</p>
              </div>
            </div>
          </div>
          
          <!-- 评价列表 -->
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div v-for="review in reviews" :key="review.id" class="bg-white border border-gray-200 rounded-2xl p-6 hover:shadow-lg transition-all duration-200 hover:-translate-y-1">
              <!-- 用户信息 -->
              <div class="flex items-start gap-4 mb-4">
                <div class="w-12 h-12 bg-gradient-to-br from-blue-400 to-purple-500 rounded-full flex items-center justify-center flex-shrink-0 shadow-sm">
                  <span class="text-sm font-medium text-white">{{ review.user.charAt(0) }}</span>
                </div>
                <div class="flex-1">
                  <h4 class="font-medium text-gray-900 mb-1">{{ review.user }}</h4>
                  <div class="flex items-center gap-2 mb-2">
                    <div class="flex">
                      <svg v-for="i in 5" :key="i" class="w-4 h-4" :class="i <= review.rating ? 'text-yellow-400' : 'text-gray-300'" fill="currentColor" viewBox="0 0 20 20">
                        <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                      </svg>
                    </div>
                    <span class="text-sm text-gray-500">{{ formatDate(review.date) }}</span>
                  </div>
                  
                  <!-- 评价标签 -->
                  <div v-if="review.tags" class="flex flex-wrap gap-1 mb-2">
                    <span v-for="tag in review.tags" :key="tag" class="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded-full">
                      {{ tag }}
                    </span>
                  </div>
                </div>
              </div>
              
              <!-- 评价内容 -->
              <div class="space-y-3">
                <p class="text-gray-600 leading-relaxed">{{ review.comment }}</p>
                
                <!-- 有用性投票 -->
                <div class="flex items-center gap-4 pt-3 border-t border-gray-100">
                  <button class="flex items-center gap-1 text-sm text-gray-500 hover:text-gray-700 transition-colors duration-200">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5" />
                    </svg>
                    <span>{{ review.helpful || 0 }}</span>
                  </button>
                  
                  <button class="flex items-center gap-1 text-sm text-gray-500 hover:text-gray-700 transition-colors duration-200">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                    </svg>
                    <span>回复</span>
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 查看更多评价 -->
          <div class="text-center mt-12">
            <button class="px-8 py-3 bg-gray-100 text-gray-700 rounded-xl hover:bg-gray-200 transition-colors duration-200 font-medium">
              查看更多评价
            </button>
          </div>
        </div>

      </div>
    </div>
  </ShopLayout>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Head, Link, router } from '@inertiajs/vue3'
import ShopLayout from '@/Layouts/ShopLayout.vue'
import SEO from '@/Components/SEO.vue'
import CompareButton from '@/Components/CompareButton.vue'
import { useSpecificationSelection } from '@/composables/useSpecificationSelection'
import { useNotification } from '@/composables/useNotification'
import { generateProductSchema, truncateDescription, generateCanonicalUrl } from '@/composables/useSEO'

// Props
const props = defineProps({
  product: {
    type: Object,
    required: true
  },
  variants: {
    type: Array,
    default: () => []
  },
  relatedProducts: {
    type: Array,
    default: () => []
  },
  systemSettings: {
    type: Object,
    default: () => ({})
  }
})

// 使用规格选择 composable
const {
  selectedSpecs,
  selectedVariant,
  currentPrice,
  currentStock,
  variantError,
  selectSpec,
  canAddToCart,
  addToCartButtonText,
  buyNowButtonText,
  getSpecOptionStockStatus
} = useSpecificationSelection(props.product, props.variants)

// 通知功能
const { showSuccess, showError } = useNotification()

// 其他响应式数据
const quantity = ref(1)
const selectedImage = ref('')

// SEO相关计算属性
const seoTitle = computed(() => {
  return props.product.meta_title || props.product.name
})

const seoDescription = computed(() => {
  return props.product.meta_description || 
         truncateDescription(props.product.description || props.product.short_description)
})

const seoKeywords = computed(() => {
  if (props.product.meta_keywords && Array.isArray(props.product.meta_keywords)) {
    return props.product.meta_keywords.join(', ')
  }
  return `${props.product.name}, Orange Tech, ${props.product.brand || ''}`
})

const seoImage = computed(() => {
  const origin = window.location.origin
  const imagePath = props.product.images?.[0]?.image_path || props.product.image || ''
  return imagePath.startsWith('http') ? imagePath : `${origin}${imagePath}`
})

const seoCanonical = computed(() => {
  return props.product.canonical_url || generateCanonicalUrl()
})

const seoAvailability = computed(() => {
  return props.product.stock_quantity > 0 ? 'in_stock' : 'out_of_stock'
})

const productSchema = computed(() => {
  return generateProductSchema(props.product, props.systemSettings)
})

// 计算属性
const averageRating = computed(() => {
  if (!props.product.reviews || props.product.reviews.length === 0) return 0
  const total = props.product.reviews.reduce((sum, review) => sum + review.rating, 0)
  return (total / props.product.reviews.length).toFixed(1)
})

// 产品规格型号（从后端获取）
const specifications = computed(() => {
  return props.product.specifications || []
})

// 产品特性（从后端获取）
const features = computed(() => {
  return props.product.features || []
})

// 技术规格（从后端获取 - technical_specs 字段）
const technicalSpecs = computed(() => {
  return props.product.technical_specs || []
})

// 用户评价（从后端获取）
const reviews = computed(() => {
  return props.product.reviews || []
})

// 这些计算属性现在由 composable 提供

// 方法
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

// selectSpec 方法现在由 composable 提供

const addToCart = () => {
  // 根据商品类型判断 variant_id
  let variantId = null
  if (props.product.product_type === 'single') {
    // 单规格商品，variant_id 始终为 null
    variantId = null
  } else {
    // 多规格商品，从选中的变体获取 variant_id
    variantId = selectedVariant.value ? selectedVariant.value.id : null
  }

  const payload = {
    product_id: props.product.id,
    variant_id: variantId,
    quantity: quantity.value,
  }

  router.post(route('cart.add'), payload, {
    preserveScroll: true,
    preserveState: false, // 允许重新加载全局共享数据（包括 cartCount）
    onSuccess: () => {
      // 显示成功提示
      showSuccess('已加入购物车！', '')
    },
    onError: (errors) => {
      // 显示错误提示
      showError('加入购物车失败', '请重试')
    }
  })
}

const buyNow = () => {
  // 检查是否选择了规格（多规格产品）
  if (props.product.product_type === 'multi_variant' && !selectedVariant.value) {
    showError('请选择商品规格', '')
    return
  }
  
  // 根据商品类型判断 variant_id
  let variantId = null
  if (props.product.product_type === 'single') {
    // 单规格商品，variant_id 始终为 null
    variantId = null
  } else {
    // 多规格商品，从选中的变体获取 variant_id
    variantId = selectedVariant.value ? selectedVariant.value.id : null
  }
  
  const payload = {
    product_id: props.product.id,
    variant_id: variantId,
    quantity: quantity.value,
  }
  
  router.post(route('checkout.buy-now'), payload, {
    preserveScroll: true,
    onSuccess: () => {
      // 成功后会自动跳转到结算页
    },
    onError: (errors) => {
      showError('操作失败', '请重试')
    }
  })
}
</script>